﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using Openfree.Framework.DataAccess;

public partial class PMSWeb_TaskSearch : PMSBase
{
    private SqlCodeConfig codeConfig;
    private string cmdText = @"select a.TaskCode,a.TaskItemID,a.TaskID,a.SNYear,a.SNGroup,a.SNTask,a.SNProject,a.SNDispatch,a.TaskState,D.CodeName as GroupName,C.Guest,C.Phone,C.Location,C.RoomNo,C.HouseNo,C.CreateDate,case when B.status='" + PMSGoodsState.NotOut + "' then '" + PMSGoodsState.GetName("" + PMSGoodsState.NotOut) + @"' when B.status='" + PMSGoodsState.IsOut + "' then '" + PMSGoodsState.GetName("" + PMSGoodsState.IsOut) + @"' else '——' end ReqStatus, (select Username from T_User where UserID=C.UserID) Username from PMS_TaskItem a 
                   left join IC_Requisition B on B.TaskID=a.TaskItemID left join PMS_TaskLX C on c.TaskID = a.TaskID left join T_CodeConfig D on D.CodeValue=a.SNGroup AND D.Category = '" + PMSCodeCategory.PMS_BMZB + "'  where 1=1  ";
    protected void Page_Load(object sender, EventArgs e)
    {
        this.TableName = "PMS_TaskItem";
        this.Key = "TaskItemID";
        if (!IsPostBack)
        {  
            this.ClearValue();
            tbPersonCode.Attributes.Add("onkeypress", "Openfree.prototype.EnterSubmit('" + tbPersonCode.ClientID + "',event);");
        }
        else
        {
            if (!string.IsNullOrEmpty(tbPersonCode.Text))
            {
                TaskPersonItem.AddSelectPerson(tbPersonCode.Text.Replace("-",""));
                tbPersonCode.Text = "";
            }
        }

        //ValidateUser2.OnValidateUser += new EventHandler(on_ValidateUser);
    }
    public void btnSearchPerson_Click(object sender, EventArgs e)
    {
        pnlSearchPerson.Visible = true;
    }
    public void InitData()
    { 
        DepTime.Text = "";
        ArrTime.Text = "";
        ddlDepHH.Text = "";
        ddlDepMM.Text = "";
        ddlArrHH.Text = "";
        ddlArrMM.Text = "";
        //获取用户意见
        codeConfig = new SqlCodeConfig(this.Connection);
        DataSet ds = codeConfig.LoadDataByCategory(PMSCodeCategory.PMS_CustomerSuggest);
        radioButtonList.Items.Clear();
        foreach (DataRow row in ds.Tables[0].Rows)
        {
            ListItem item = new ListItem();
            item.Text = row["CodeName"].ToString();
            item.Value = row["CodeValue"].ToString();
            radioButtonList.Items.Add(item);
        } 
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(S_TaskCode.Text.Trim()))
        {
            this.ClearValue();
            return;
        }
        tipMessage1.ShowMessage("", 5000);
        StringBuilder sql = new StringBuilder(cmdText);
        sql.Append(" AND a.TaskCode = '").Append(S_TaskCode.Text.Trim().Replace("-", "")).Append("'");
        sql.Append(" order by a.TaskState asc,C.CreateDate desc");
        DataSet ds = PMSAccess.GetDataSet(this.Connection,sql.ToString());
        ClearValue();
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            DataRow row = ds.Tables[0].Rows[0];
            int state = Convert.ToInt32(row["TaskState"]);
            hfTaskID.Value = row["TaskItemID"].ToString();
            if (state == PMSTaskState.Complete || state == PMSTaskState.IsRemove)
            { 
                pnlTaskInfo.Visible = true; 
                pnlToolbar.Visible = false;
                View();
            }
            else
            { 
                pnlTaskInfo.Visible = true; 
                pnlToolbar.Visible = true;
                on_ValidateUser(sender, e);
            }
        } 
    } 
       
    private void ClearValue()
    {
        tbGuest.Text = "";
        tbRoomNo.Text = "";
        cbHouseNo.Text = "";
        tbPhone.Text = "";
        tbTroubleDescription.Text = "";
        lbUserID.Text = SessionManager.LoginName;
        lbOrgID.Text = SessionManager.OrgName;
        cbIsReqGood.Checked = false;
        pnlSearchPerson.Visible = false;
        lbCreateDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
        this.InitData();
        hfTaskID.Value = "";
        //显示领单人 
        InitGridReceiverView(System.Guid.NewGuid().ToString());
        DataSet ds = PMSAccess.GetDataSet(this.Connection, "select (select top 1 OutTime from PMS_TaskUser where TaskID=A.TaskItemID) as OutTime,(select top 1 CustomerSuggest from PMS_TaskUser where TaskID=A.TaskItemID) as CustomerSuggest,A.*,B.Guest,B.Location,B.RoomNo,B.HouseNo,B.Phone,B.TroubleDescription,B.OrgID,B.UserID,B.CreateDate,B.IsRequestGood FROM PMS_TaskItem A inner join PMS_TaskLX B on A.TaskID=B.TaskID where A.TaskItemID='" + System.Guid.NewGuid().ToString() + "'", this.TableName);

        SessionManager.DataSet = ds;
        TaskPersonItem.ShowWorkTime = true;
        TaskPersonItem.IsReadOnly = false;
        TaskPersonItem.InitData("TaskID", System.Guid.NewGuid().ToString(), string.Empty);

        pnlToolbar.Visible = false; 
        pnlTaskInfo.Visible = false; 
    }
     
    protected void View()
    {

        string taskItemID = hfTaskID.Value;
        hfAddOrEdit.Value = "View";
        DataSet ds = PMSAccess.GetDataSet(this.Connection, "select (select top 1 OutTime from PMS_TaskUser where TaskID=A.TaskItemID) as OutTime,(select top 1 CustomerSuggest from PMS_TaskUser where TaskID=A.TaskItemID) as CustomerSuggest,A.*,B.Guest,B.Location,B.RoomNo,B.HouseNo,B.Phone,B.TroubleDescription,B.OrgID,B.UserID,B.CreateDate,B.IsRequestGood FROM PMS_TaskItem A inner join PMS_TaskLX B on A.TaskID=B.TaskID where A.TaskItemID='" + taskItemID + "'", this.TableName);

        SessionManager.DataSet = ds;

        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        } 
        DataRow row = ds.Tables[0].Rows[0];
        if (!string.IsNullOrEmpty(row["StartTime"].ToString()) && !string.IsNullOrEmpty(row["EndTime"].ToString()))
        {
            DateTime sdt = Convert.ToDateTime(row["StartTime"].ToString());
            DepTime.Text = sdt.ToString("yyyy-MM-dd");
            ddlDepHH.Text = sdt.Hour.ToString("00");
            ddlDepMM.Text = sdt.Minute.ToString("00");
            DateTime edt = Convert.ToDateTime(row["EndTime"].ToString());
            ArrTime.Text = edt.ToString("yyyy-MM-dd");
            ddlArrHH.Text = edt.Hour.ToString("00");
            ddlArrMM.Text = edt.Minute.ToString("00");
            ddlHHdis.Text = row["OutTime"].ToString();
            radioButtonList.SelectByValue = row["CustomerSuggest"].ToString();
        }
        tbHandling.Text = row["Handling"].ToString();

        //显示领单人
        InitGridReceiverView(taskItemID);

        //tabsMenu.SelectedIndex = 0;

        SessionManager.DataSet = ds;
        TaskPersonItem.ShowWorkTime = true;
        TaskPersonItem.IsReadOnly = true;
        TaskPersonItem.InitData("TaskID", taskItemID, string.Empty);

        UserAccess user = new UserAccess(base.Connection);
        tbGuest.Text = row["Guest"].ToString();
        tbRoomNo.Text = row["RoomNo"].ToString();
        cbHouseNo.Text = row["HouseNo"].ToString();
        tbPhone.Text = row["Phone"].ToString();
        tbTroubleDescription.Text = row["TroubleDescription"].ToString();
        lbOrgID.Text = user.GetUserOrgName(row["OrgID"].ToString());
        lbUserID.Text = user.GetUserNameByUserID(row["UserID"].ToString());
        cbIsReqGood.Checked = Convert.ToBoolean(row["IsRequestGood"]);
        lbCreateDate.Text = Convert.ToDateTime(row["CreateDate"].ToString()).ToString("yyyy-MM-dd HH:mm");

        SetTaskReadOnly(true);
    }
    private void SetTaskReadOnly(bool flag)
    {
        DepTime.ReadOnly = flag;
        ArrTime.ReadOnly = flag;
        ddlHHdis.ReadOnly = flag;
        tbHandling.ReadOnly = flag;
        radioButtonList.Enabled = !flag;
        btnSelect.Visible = !flag;
        btnSave.Visible = !flag;
    }

    private void on_ValidateUser(object sender, EventArgs e)
    {
        //0用户名密码错误，1正确，2用户被锁定
        //if ("0".Equals(sender.ToString()))
        //{
        //    tipMessage1.ShowMessage("用户名密码错误", 5000);
        //    return;
        //}

        //if ("2".Equals(sender.ToString()))
        //{
        //    tipMessage1.ShowMessage("用户被锁定", 5000);
        //    return;
        //}
        //SecurityAccess securityAccess = new SecurityAccess(base.Connection);
        //DataSet dsRule = securityAccess.GetUserRule(ValidateUser2.GetUserID());
        //if (dsRule.Tables[0].Select("ContainerName='RWDFHQR'").Length == 0)
        //{   // 授权项： RWDFHQR 任务单返还确认 
        //    tipMessage1.ShowMessage("用户权限不足", 5000);
        //    return;
        //}
 
        DataSet ds = PMSAccess.GetDataSet(this.Connection, "select A.*,B.Guest,B.Location,B.RoomNo,B.HouseNo,B.Phone,B.TroubleDescription,B.OrgID,B.UserID,B.CreateDate,B.IsRequestGood FROM PMS_TaskItem A inner join PMS_TaskLX B on A.TaskID=B.TaskID where A.TaskItemID='" + hfTaskID.Value + "'", this.TableName);
        SessionManager.DataSet = ds;

        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        }
        DataRow row = ds.Tables[0].Rows[0];
        if (Convert.ToInt32(row["TaskState"]) == PMSTaskState.Complete)
        {
            Alert("您选择的任务已经完成，不能再进行操作！");
            return;
        }
        if (Convert.ToInt32(row["TaskState"]) == PMSTaskState.IsRemove)
        {
            Alert("您选择的任务已经作废，不能再进行操作！");
            return;
        }
        if (!string.IsNullOrEmpty(row["StartTime"].ToString()) && !string.IsNullOrEmpty(row["StartTime"].ToString()))
        {
            DateTime sdt = Convert.ToDateTime(row["StartTime"].ToString());
            DepTime.Text = sdt.ToString("yyyy-MM-dd");
            ddlDepHH.Text = sdt.Hour.ToString("00");
            ddlDepMM.Text = sdt.Minute.ToString("00");
            DateTime edt = Convert.ToDateTime(row["EndTime"].ToString());
            ArrTime.Text = edt.ToString("yyyy-MM-dd");
            ddlArrHH.Text = edt.Hour.ToString("00");
            ddlArrMM.Text = edt.Minute.ToString("00");
            ddlHHdis.Text = "" + 0;
        }
        else
        {
            DateTime sdt = DateTime.Now;
            DepTime.Text = sdt.ToString("yyyy-MM-dd");
            ArrTime.Text = sdt.ToString("yyyy-MM-dd");
            ddlDepHH.Text = "00";
            ddlDepMM.Text = "00";
            ddlArrHH.Text = "00";
            ddlArrMM.Text = "00";
        }
        tbHandling.Text = row["Handling"].ToString();
        SetTaskReadOnly(false);
 
        pnlEdit.Visible = true;

        //显示领单人
        InitGridReceiverView(hfTaskID.Value);

        SessionManager.DataSet = ds;
        TaskPersonItem.ShowWorkTime = true;
        TaskPersonItem.IsReadOnly = false;
        TaskPersonItem.InitData("TaskID", hfTaskID.Value, string.Empty);

        UserAccess user = new UserAccess(base.Connection);
        tbGuest.Text = row["Guest"].ToString();
        tbRoomNo.Text = row["RoomNo"].ToString();
        cbHouseNo.Text = row["HouseNo"].ToString();
        tbPhone.Text = row["Phone"].ToString();
        tbTroubleDescription.Text = row["TroubleDescription"].ToString();
        lbOrgID.Text = user.GetUserOrgName(row["OrgID"].ToString());
        lbUserID.Text = user.GetUserNameByUserID(row["UserID"].ToString());
        cbIsReqGood.Checked = Convert.ToBoolean(row["IsRequestGood"]);
        lbCreateDate.Text = Convert.ToDateTime(row["CreateDate"].ToString()).ToString("yyyy-MM-dd HH:mm");
    } 
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt32(ddlDepHH.Text.Trim()) > 23 || Convert.ToInt32(ddlArrHH.Text.Trim()) > 23)
        {
            Alert("小时数不超过23");
            return;
        }
        if (Convert.ToInt32(ddlDepMM.Text.Trim()) > 60 || Convert.ToInt32(ddlArrMM.Text.Trim()) > 60)
        {
            Alert("分钟数不超过60");
            return;
        }
        //判断是否选择派修人员
        TaskPersonItem.ShowWorkTime = true;
        string result = TaskPersonItem.PreProcessSave();
        if (!string.IsNullOrEmpty(result))
        {
            tipMessage1.ShowMessage(result, 5000);
            return;
        }
        DataTable dt = null;
        StringBuilder str = new StringBuilder();
        if (SessionManager.DataSet.Tables.Contains(TaskPersonItem.m_TableName))
        {
            dt = SessionManager.DataSet.Tables[TaskPersonItem.m_TableName];
            foreach (DataRow dr in dt.Rows)
            {
                if (dr.RowState != DataRowState.Deleted)
                {
                    str.Append(",'").Append(dr["UserID"].ToString()).Append("'");
                    dr["TaskID"] = hfTaskID.Value;
                    dr["UserType"] = PMSCodeCategory.UserWorker;
                    dr["UpdateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                    dr["UpdateUser"] = ValidateUser2.GetUserID();
                    dr["OutTime"] = string.IsNullOrEmpty(ddlHHdis.Text) ? 0 : Convert.ToInt32(ddlHHdis.Text);
                    dr["CustomerSuggest"] = radioButtonList.SelectedValue;
                }
            }
        }
        DataRow row = SessionManager.DataSet.Tables[this.TableName].Rows[0];
        row["TaskState"] = PMSTaskState.Complete;
        row["StartTime"] = DepTime.Text + " " + ddlDepHH.Text.Trim() + ":" + ddlDepMM.Text.Trim();
        row["EndTime"] = ArrTime.Text + " " + ddlArrHH.Text.Trim() + ":" + ddlArrMM.Text.Trim();
        row["Handling"] = tbHandling.Text;
        row["UpdateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
        row["UpdateUser"] = ValidateUser2.GetUserID();

        PMSAccess.UpdateDataSet(this.Connection, new string[] { this.TableName, "PMS_TaskUser" }, SessionManager.DataSet);

        if (str.Length > 0)
        {
            PMSAccess.ExecuteNonQuery(this.Connection, "update PMS_User set IsWorking=IsWorking-1 where UserId in (" + str.Remove(0, 1).ToString() + ")");
        }
        this.ClearValue();
        this.S_TaskCode.Text = "";
        tipMessage1.ShowMessage("任务完成", 5000);
    }

    protected void btnDocument_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(hfTaskID.Value))
            return;
        tipMessage1.ShowMessage("", 5000);
        string taskID = hfTaskID.Value;
        string filePath = Server.MapPath(SessionManager.TempVirtualFolder + System.Guid.NewGuid().ToString() + ".doc");
        string outinfo = DocumentHelper.ExportDispatchDocument(PMSConst.PMSDispatchDocTemplatePath, filePath, taskID);
        if (string.IsNullOrEmpty(outinfo))
        {
            ifdown.Attributes["src"] = "../SiteAdmin/DownLoadHandler.ashx?url=" +
                filePath + "&name=" + HttpUtility.UrlEncode("派工单.") + DateTime.Now.ToString("MMdd.HHmmss") + ".doc";
            //base.DownLoadFile(filePath, "派工单.doc");
        }
        else
        {
            tipMessage1.ShowMessage(outinfo, 5000);
        }
    } 
    protected void btnSelect_Click(object sender, EventArgs e)
    {
        if (TaskPersonItem.OnSelect != null)
        {
            TaskPersonItem.ShowWorkTime = true;
            TaskPersonItem.IsReadOnly = false;
            TaskPersonItem.OnSelect(sender, e);
            TaskPersonItem.SetGroupReadOnly(hfCurrentGroupCode.Value);
        }
    } 

    #region 显示领单人信息
    protected void InitGridReceiverView(string taskId)
    {
        string cmdItemsText = @"SELECT T.*,A.Username,A.GroupCode,A.Mobile,B.OrgID,D.Subject as OrgName,C.CodeName as GroupName  FROM PMS_TaskUser T inner join PMS_User A on A.UserID = T.UserID 
                    left join T_OrgUser B on B.UserID = T.UserID 
                    left join  T_CodeConfig C on C.CodeValue=A.GroupCode  AND C.Category = '" + PMSCodeCategory.PMS_BMZB + @"' 
                    left join T_OrgTree D on D.OrgID=B.OrgID where 1=1 and T.UserType='" + PMSCodeCategory.UserReceiver + "' and T.TaskID='" + taskId + "'";

        DataSet ds = PMSAccess.GetDataSet(this.Connection, cmdItemsText);
        if (ds.Tables[0].Rows.Count > 0)
        {
            hfCurrentGroupCode.Value = ds.Tables[0].Rows[0]["GroupCode"].ToString();
        }
        gridReceiverView.DataSource = ds.Tables[0];
        gridReceiverView.ShowFooter = false;
        gridReceiverView.DataBind();
    }
    #endregion
}
